package zunge.pmp2;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.HashMap;

import zunge.tools.DbConn;

public class PmpCsvParser {
	
	public static void main(String args[]){
		
		try{
			DbConn conn = new DbConn("127.0.0.1", "pmp2","root","sergeypk428571");
			
			conn.executeQuery("set names utf8mb4;");
			conn.executeQuery("set character set utf8mb4;");
	
			PreparedStatement ps = conn.getPreparedStatement(
					"insert into init_records (timestamp, a_id, version, u_id, feature, "
					+ "protect, source, recommend, app_name) values "
					+ "(?,?,?,?,?,?,?,?,?)");
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			
			String f_in = "/usr0/home/bliu1/BinWork/Workspace/PMP_1/data/protect.csv";
			BufferedReader br = new BufferedReader(
					new InputStreamReader(new FileInputStream(f_in), "utf-8"));
			String line=br.readLine();//skip header
			while((line=br.readLine())!=null){
				try{
					int pivot = line.indexOf("\"");
					if(pivot==-1){
						line = line + br.readLine();
						pivot = line.indexOf("\"");
					}
					String left = line.substring(0, pivot-1);
					String right = line.substring(pivot+1, line.length()-1);
					
					String[] frags = left.split(",");
					ps.setLong(1, sdf.parse(frags[1]).getTime()/1000);
					ps.setInt(2, Integer.parseInt(frags[2]));
					ps.setString(3, frags[3]);
					ps.setInt(4, Integer.parseInt(frags[4]));
					ps.setString(5, frags[5]);
					ps.setInt(6, Integer.parseInt(frags[6]));
					ps.setInt(7, Integer.parseInt(frags[7]));
					if(frags.length<9){
						ps.setInt(8, 2);
					}else{
						ps.setInt(8, Integer.parseInt(frags[8]));
					}
					ps.setString(9, right);
					conn.executeUpdate(ps);
				}catch(Exception e){
					e.printStackTrace();
					System.err.println(line);
					continue;
				}
				
			}
			br.close();
			
			conn.close();
			
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
